// -----------------------------------------------------------------------
//  <copyright file="MediatRModule.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2023 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2023-12-21 13:00</last-date>
// -----------------------------------------------------------------------

using DaprPlus.AspNetCore.Mvc.Filters;
using DaprPlus.MediatR.Behaviors;

using FluentValidation;


namespace DaprPlus.MediatR;

public abstract class MediatRModuleBase : ModuleBase
{
    /// <summary>
    /// 获取 模块级别，级别越小越先启动
    /// </summary>
    public override ModuleLevel Level => ModuleLevel.Application;

    /// <summary>
    /// 重写以提供注册MediatR和FluentValidation的程序集
    /// </summary>
    protected virtual Assembly[] Assemblies => [Assembly];

    /// <summary>
    /// 将模块服务添加到依赖注入服务容器中
    /// </summary>
    /// <param name="services">依赖注入服务容器</param>
    /// <returns></returns>
    public override IServiceCollection AddServices(IServiceCollection services)
    {
        var assemblies = Assemblies.ToList();
        assemblies.Add(typeof(MediatRModuleBase).Assembly);
        services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(assemblies.ToArray()));
        services.AddValidatorsFromAssemblies(assemblies);

        services.AddScoped<IDomainEventBus, DomainEventBus>();

        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(LoggingBehavior<,>));
        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(AuthorizationBehavior<,>));
        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(TransactionBehavior<,>));

        services.AddSingleton<IApiResultExceptionHandler, ValidationExceptionHandler>();
        return services;
    }
}
